package com.dongdong.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.pojo.TbGoods;
import com.dongdong.pojo.TbGoodsDesc;
import com.dongdong.pojo.TbItem;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/17 19:04
 * @Version 1.0
 **/
@Service
public class FreeMarketServiceImpl implements FreeMarketService{

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${freemarker.outDir}")
    private String outDir;

    @Reference
    private GoodsService goodsService;

    @Reference
    private GoodsDescService goodsDescService;

    @Reference
    private ItemService itemService;

    @Override
    public void createItemPage(Long goodsId) {
        //获取Configuration对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        FileWriter fileWriter = null;
        try {
            //获取template模板对象
            Template template = configuration.getTemplate("item.ftl");

            //查询goods表信息 根据id查询
            TbGoods goods = goodsService.findGoodsById(goodsId);
            TbGoodsDesc goodsDesc = goodsDescService.findGoodsDescById(goodsId);
            List<TbItem> itemList = itemService.findItemListByGoodsId(goodsId);
            //创建数据模型
            Map map = new HashMap();
            map.put("goods",goods);
            map.put("goodsDesc",goodsDesc);
            map.put("itemList",itemList);

            //创建输出对象Writer
            fileWriter = new FileWriter(outDir + goodsId + ".html");//参数是我们想要把我们的生成的页面放在哪
            //输出页面
            template.process(map,fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭流
            try {
                if (fileWriter != null){
                    fileWriter.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }
}

